﻿using Newtonsoft.Json;
using System;
using System.IO;

namespace Mbs.Utils
{
    public static class CacheService<T>
    {
        private static readonly string CacheDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache");
        private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
        {
            Formatting = Formatting.Indented
        };
        /// <summary>
        /// 保存数据到缓存文件
        /// </summary>
        public static void Save(string cacheKey, T data, TimeSpan? expiry = null)
        {
            if (!Directory.Exists(CacheDir))
                Directory.CreateDirectory(CacheDir);
            var cacheFile = Path.Combine(CacheDir, $"{cacheKey}.json");
            var cacheData = new CacheWrapper<T>
            {
                Data = data,
                ExpiryTime = DateTime.Now.Add(expiry ?? TimeSpan.FromHours(1))
            };
            File.WriteAllText(cacheFile, JsonConvert.SerializeObject(cacheData, SerializerSettings));
        }
        /// <summary>
        /// 从缓存文件加载数据（自动检查有效期和完整性）
        /// </summary>
        public static (bool IsValid, T Data) Load(string cacheKey)
        {
            var cacheFile = Path.Combine(CacheDir, $"{cacheKey}.json");
            if (!File.Exists(cacheFile)) return (false, default);
            try
            {
                var json = File.ReadAllText(cacheFile);
                var wrapper = JsonConvert.DeserializeObject<CacheWrapper<T>>(json);
                // 检查是否过期或被篡改
                if (wrapper == null || wrapper.ExpiryTime < DateTime.Now)
                    return (false, default);
                return (true, wrapper.Data);
            }
            catch
            {
                // 文件损坏或格式错误
                return (false, default);
            }
        }
        private class CacheWrapper<TData>
        {
            public TData Data { get; set; }
            public DateTime ExpiryTime { get; set; }
        }
    }
}
